<template>
  <div class="container">
    <el-card style="width: 500px; margin-left: auto; margin-right: auto;">


      <el-row>
        <el-col :span="8"></el-col>
        <el-col :span="8" class="text-center">
          <div class="centered-text">注册</div>
        </el-col>
        <el-col :span="8"></el-col>
      </el-row>

      <el-form ref="ruleFormRef"
        style="max-width: 600px; display: flex; flex-direction: column; align-items: center; margin: 20px auto 0;"
        :model="ruleForm" status-icon :rules="rules" label-width="auto" class="demo-ruleForm">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model.trim="ruleForm.nickname" autocomplete="off" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="ruleForm.email" autocomplete="off" />
        </el-form-item>

        <el-form-item label="密码" prop="pass">
          <el-input v-model.trim="ruleForm.pass" type="password" autocomplete="off" />
        </el-form-item>

        <el-form-item label="确认密码" prop="checkPass">
          <el-input v-model.trim="ruleForm.checkPass" type="password" autocomplete="off" />
        </el-form-item>

        <el-form-item label="验证码" prop="verifyCode">
          <el-row>
            <el-col :span="16">
              <el-input v-model.trim="ruleForm.verifyCode" style="width: 100px;" />
            </el-col>
            <el-col :span="8">
              <el-button type="primary" plain @click="sendRegisterVerifyCode">{{ sendCodeButtonText }}</el-button>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            注册
          </el-button>
        </el-form-item>
      </el-form>

      <div style="text-align: center;">
        <el-link type="primary" @click="goToLogin">已有账号？去登录</el-link>
      </div>

    </el-card>
  </div>
</template>


<script lang="ts" setup>
import { ref, reactive } from "vue";
import { FormInstance, FormRules, ElNotification } from "element-plus";
import { useRouter } from "vue-router";

import { register, sendVerifyCode } from '@/api/user';


//路由
const router = useRouter();



const ruleFormRef = ref<FormInstance>();

const checkNickname = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("请输入昵称"));
  }
  setTimeout(() => {
    if (value.length < 3) {
      callback(new Error("昵称至少3个字符"));
    } else {
      if (value.length > 10) {
        callback(new Error("昵称最长10个个字符"));
      } else {
        callback();
      }
    }
  }, 1000);
};

const checkEmail = (rule: any, value: any, callback: any) => {
  let reg =
    /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
  if (!reg.test(value)) {
    return callback(new Error("邮箱格式错误"));
  } else if (value.length > 50) {
    return callback(new Error("不支持超过50个字符的邮箱地址"));
  }
  callback();
};

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输出密码"));
  } else {
    if (ruleForm.checkPass !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("checkPass");
    }
    callback();
  }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请再次输出密码"));
  } else if (value !== ruleForm.pass) {
    callback(new Error("Two inputs don't match!"));
  } else {
    callback();
  }
};

// 验证码应该全为数字
const validateVerifyCode = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入验证码"));
  } else if (!/^\d+$/.test(value)){
    callback(new Error("验证码由数字组成"));
  } else if (value.length != 6) {
    callback(new Error("验证码为6位"));
  } 
  else {
    callback();
  }
};



const ruleForm = reactive({
  nickname: "",
  email: "",
  pass: "",
  checkPass: "",
  verifyCode: "",
});

const rules = reactive<FormRules<typeof ruleForm>>({
  nickname: [{ validator: checkNickname, trigger: "blur" }],
  email: [{ validator: checkEmail, trigger: "blur" }],
  pass: [{ validator: validatePass, trigger: "blur" }],
  checkPass: [{ validator: validatePass2, trigger: "blur" }],
  verifyCode: [{ validator: validateVerifyCode, trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      console.log("submit!");



      register(ruleForm.nickname, ruleForm.email, ruleForm.pass, ruleForm.verifyCode)
        .then(result => {
          console.log(result.data.code);
          console.log("to login");
          router.push("/login");

        })
        .catch((error) => {
          console.log('error' + error);
        })

    } else {
      console.log("error submit!");
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};



let number = 60;
const disableSendCodeButton = ref(false);
let timer;
const sendCodeButtonText = ref('发送验证码');
let fn = function () {
  if (number <= 0) {
    sendCodeButtonText.value = '重新获取';
    disableSendCodeButton.value = false;
    number = 60;

    // 清除定时器
    clearInterval(timer);
  } else {
    disableSendCodeButton.value = true;
    sendCodeButtonText.value = --number + 's后重新获取'

  }
};

const sendRegisterVerifyCode = () => {
  if (ruleForm.email != '') {
        if (!disableSendCodeButton.value) {
            sendVerifyCode(ruleForm.email);

            fn();
            timer = setInterval(fn, 1000);
        }
    }
    else {
        ElNotification({
            title: '请先输入邮箱',
            message: '请先输入邮箱',
            type: 'error',
        })
    }

}

const goToLogin = () => {
  router.push('/login');
}

</script>


<style scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 95vh;
}

.text-center {
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
  height: 100%;
  /* 确保有足够的高度进行垂直居中 */
  /* 如果需要，可以添加一些内边距或边框来美化 */
  padding: 10px 0;
  /* 上下内边距 */
}

.centered-text {
  font-size: 20px;
  font-weight: bold;
  color: blue;
}
</style>